<?php

App::uses('AdminController', 'Controller');

class AdminCommentsController extends AdminController {
	
	public $uses = array('CustomerComment');
	
	public $paginate = array(
		'limit' => ITEMS_PER_PAGE,
		'order' => 'id DESC'
	);
	
	public function index() {
		$this->set("comments", $this->paginate('CustomerComment'));
	}
	
	public function create() {
		$this->set("comment", $this->CustomerComment->create());
		$this->render("form");
	}
	
	public function edit($id) {
		$this->set("comment", $this->CustomerComment->findById($id));
		$this->render("form");
	}
	
	public function save() {
		if(!empty($this->data)) {
			$data = $this->data;
			
			$toupload = false;
			if(!$data['CustomerComment']['file']['error']) {
				$data['CustomerComment']['image'] = $data['CustomerComment']['file']['name'];
				$toupload = $data['CustomerComment']['file'];
			}
			
			$this->CustomerComment->create($data);
			if($this->CustomerComment->validates()) {
				if($this->CustomerComment->save($data)) {
					if($toupload) {
						upload($toupload['tmp_name'], 'img' . DS . 'customers' . DS . $toupload['name']);
					}
					$this->setFlash('Komentar je sačuvan.', 'ok');
					$this->redirect('/admin_comments/edit/' . $this->CustomerComment->id);
				}else{
					$this->setFlash('Čuvanje komentara nije uspelo.');
					return $this->render('form');
				}
			}else{
				$this->setFlash('Uneti podaci nisu validni.');
				$this->set("comment", $data);
				return $this->render('form');
			}
		}
		
		$this->redirect('index');
	}
	
	public function delete($id) {
		if($comment = $this->CustomerComment->findById($id)) {
			if($this->CustomerComment->delete($id)) {
				if(!empty($comment['CustomerComment']['image'])) {
					@unlink('img' . DS . 'customers' . DS . $comment['CustomerComment']['image']);
				}
				$this->setFlash("Komentar je obrisan");
			}else{
				$this->setFlash("Komentar nije obrisan");
			}			
		}
		$this->redirect("index");
	}
	
}